import java.util.*;

public class Main {

    public static int n;
    public static int k;
    public static int[][] arr;
    public static boolean[][] flag;
    public static Queue<int[]> queue = new LinkedList<>();
    public static List<Integer> list = new ArrayList<>();
    public static int[] temp;
    public static int[] dx = new int[]{-1, -1, 0, 1, 1, 1, 0, -1};
    public static int[] dy = new int[]{0, 1, 1, 1, 0, -1, -1, -1};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        n = sc.nextInt();
        k = sc.nextInt();
        arr = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                arr[i][j] = sc.nextInt();
            }
        }

        temp = new int[k];
        for (int i = 0; i < k; i++) {
            temp[i] = i - 1;
        }

        flag = new boolean[n][n];

        queue.offer(new int[]{0, 0});
        flag[0][0] = true;

        boolean flag1 = bfs();
        if (flag1) {
            for (int num : list) {
                System.out.print(num);
            }
        } else {
            System.out.println(-1);
        }

        sc.close();
    }

    public static boolean bfs() {

        int count = 1;

        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                size--;
                int[] arr1 = queue.poll();
                int x = arr1[0];
                int y = arr1[1];
                flag[x][y] = true;
                for (int i = 0; i < 8; i++) { //i 表示方位
                    int xx = x + dx[i];
                    int yy = y + dy[i];
                    if (xx >= 0 && xx < n && yy >= 0 && yy < n && !flag[xx][yy] && arr[xx][yy] == count) {
                        queue.offer(new int[]{xx, yy});
                        list.add(i);
                        flag[xx][yy] = true;
                    }
                    if (xx == (n - 1) && yy == (n - 1)) {
                        return true;
                    }
                }
                count = (count + 1) % k;
            }
        }

        return false;
    }
}
